package com.shadow.web.back;

import com.shadow.domain.User;
import com.shadow.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by qq65827 on 2014/10/26.
 */
@Controller
@RequestMapping(value = "user")
public class UserController extends BaseViewController {

    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @RequestMapping("index")
    public ModelAndView index(HttpServletRequest request, ModelAndView modelAndView) {
        String path = request.getContextPath();
        modelAndView.addObject("path", path);
        return JspLocation(modelAndView, "index");
    }

    @RequestMapping(value = "register", method = RequestMethod.GET)
    public ModelAndView register(ModelAndView modelAndView) {
        System.out.println("----");
        return JspLocation(modelAndView, "register");
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView login(ModelAndView modelAndView) {
        System.out.println("----");
        return JspLocation(modelAndView, "login");
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(String username, String password,ModelAndView modelAndView) {
        logger.info("log");
        Boolean isPermit = userService.isPermit(username, password);
        if (isPermit) {
            modelAndView.setViewName("user/success");
        } else {
            modelAndView.setViewName("user/fail");
        }
        return modelAndView;

    }


    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ModelAndView register(String username, String password, ModelAndView modelAndView) {
        User user = new User(username, password);
        userService.save(user);
        modelAndView.setViewName("user/success");
        return modelAndView;
    }

    @RequestMapping(value = "success")
    public ModelAndView success(ModelAndView modelAndView) {
        return JspLocation(modelAndView, "success");
    }

    @Override
    protected String getJspLocation() {
        return "/user/";
    }
}
